﻿using System;
using System.Collections.Generic;
using System.Linq;
using Basic.Model;
using Common.Library;
using Common.Model;
using Container.Library;
using Dapper.Library;
using Dapper.Library.DataAccessSql;
using Dapper.PostgreSql.Library;
using Serialize.Library;

/*
* 命名空间: Basic.Logic
*
* 功 能： 操作记录日志逻辑类
*
* 类 名： OperationLogServiceImpl
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2020/03/17 14:34:43 李聪     创建
*
* Copyright (c) 2020 Lir Corporation. All rights reserved.
*/

namespace Basic.Logic
{
    /// <summary>
    /// 异常日志逻辑类
    /// </summary>
    public class ExceptionLogServiceImpl : OperationLogicImpl, IExceptionLogService
    {

        /// <summary>
        /// 获取异常日志类型Select列表信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<EnumToSelectItem>> LoadLogTypeList()
        {

            var resultInfo = new ResultJsonInfo<List<EnumToSelectItem>>();
            resultInfo.Data = EnumToSelectItem.GetEnumDescriptionList(typeof(ExceptionLogType), true);
            resultInfo.Code = ActionCodes.Success;
            resultInfo.Msg = "获取成功！";

            return resultInfo;
        }

        #region 异常日志基础模块管理

        #region 查询
        /// <summary>
        /// 根据异常日志条件分页获取列表 关键字【异常标题】【操作明细】
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<ExceptionLogInfoResponse>> LoadExceptionList(ParametersInfo<ExceptionLogQueryRequest> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<ExceptionLogInfoResponse>>();

            //异常日志，直接操作Redis数据库
            ExceptionLogServiceRedis.GetAllExceptionLog((result) =>
            {
                if (inputInfo.parameters.exception_type > 0)
                {
                    result=result.Where(p => p.exception_type.Equals(inputInfo.parameters.exception_type)).ToList();
                }
                if (inputInfo.parameters.system_type > 0)
                {
                    result=result.Where(p => p.system_type.Equals(inputInfo.parameters.system_type)).ToList();
                }
                if (inputInfo.parameters.sKeyWords.IsNotNullOrEmpty())
                {
                    result = result.Where(a => a.exception_title.Contains(inputInfo.parameters.sKeyWords) || a.detail.Contains(inputInfo.parameters.sKeyWords)).ToList();
                }
                var listInfo = result.OrderByDescending(p => p.create_date)
                                    .Skip((inputInfo.page-1)* inputInfo.limit).Take(inputInfo.limit)
                                    .ToList();

                if (listInfo.Count > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.MapToList<ExceptionLogInfoResponse>();
                    resultInfo.Count = result.Count;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            },
            () =>
            {
                resultInfo.Msg = "无对应信息！";
            });
            return resultInfo;
        }
        #endregion

        /// <summary>
        /// 批量删除异常日志
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(ExceptionLogRequest request)
        {
            var resultInfo = new ResultJsonInfo<int>();

            ExceptionLogServiceRedis.GetAllExceptionLog((result) =>
            {
                var time = request.endTime.AddDays(1);

                var listInfo = result.Where(p => p.create_date >= request.startTime && p.create_date < time).Select(p=>p.id).ToList();
                if (listInfo.Count > 0)
                {
                    ExceptionLogServiceRedis.RemoveExceptionLog(listInfo);
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "操作成功！";
                    AddOperationLog(OperationLogType.RemoveOperation, BusinessTitleType.LogManage, $"删除异常日志信息:{JsonHelper.ToJson(request)}");
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            },
            () =>
            {
                resultInfo.Msg = "无对应信息！";
            });
            return resultInfo;
        }

        /// <summary>
        /// 解决完成异常
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> SolveException(string  id)
        {
            var resultInfo = new ResultJsonInfo<int>();

            ExceptionLogServiceRedis.GetExceptionLog(id,(exceptionLog) =>
            {
                exceptionLog.status =(int)ExceptionLogStatus.resolved;

                var result=  ExceptionLogServiceRedis.ModifyExceptionLog(id, exceptionLog);

                if (result)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "操作成功！";
                    AddOperationLog(OperationLogType.ModifyOperation, BusinessTitleType.LogManage, $"解决异常日志信息:{JsonHelper.ToJson(id)}");
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            },
            () =>
            {
                resultInfo.Msg = "无对应信息！";
            });
            return resultInfo;
        }

        #endregion

        #region 异常日志统计相关逻辑

        /// <summary>
        /// 获取对应时间段内，异常信息数量
        /// </summary>
        /// <param name="beginTime">起始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns></returns>
        public ResultJsonInfo<ExceptionCountResponse> LoadExceptionCount(DateTime beginTime, DateTime endTime)
        {

            var resultInfo = new ResultJsonInfo<ExceptionCountResponse>();

            if (beginTime == null)
            {
                beginTime = DateTime.Now.AddDays(-7);
            }
            if (endTime == null)
            {
                endTime = DateTime.Now;
            }
            //异常日志，直接操作Redis数据库
            ExceptionLogServiceRedis.GetAllExceptionLog((result) =>
            {

                var exceptionInfo = result.Where(p => p.create_date >= beginTime && p.create_date <= endTime)
                                    .Select(p => new SysExceptionLogInfoEntity()
                                    {
                                        id = p.id,
                                        status = p.status
                                    }).ToList();
                if (exceptionInfo.Count > 0)
                {
                    resultInfo.Data = new ExceptionCountResponse()
                    {
                        total = exceptionInfo.Count,
                        unresolved_count = exceptionInfo.FindAll(p => p.status == (int)ExceptionLogStatus.unresolved).Count
                    };
                    resultInfo.Code = ActionCodes.Success;
                }
                else
                {
                    resultInfo.Data = new ExceptionCountResponse();
                    resultInfo.Msg = "无对应信息！";
                }
            },
            () =>
            {

                resultInfo.Data = new ExceptionCountResponse();
                resultInfo.Msg = "无对应信息！";
            });
            return resultInfo;
        }

        /// <summary>
        /// 获取最新5条操作信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<ExceptionLogInfoResponse>> LoadLatestList()
        {
            var resultInfo = new ResultJsonInfo<List<ExceptionLogInfoResponse>>();


            //异常日志，直接操作Redis数据库
            ExceptionLogServiceRedis.GetAllExceptionLog((result) =>
            {

                var listInfo = result.OrderByDescending(p => p.create_date)
                                    .Skip(0).Take(4)
                                    .ToList();

                if (listInfo.Count > 0)
                {
                    var logInfoList = listInfo.MapToList<ExceptionLogInfoResponse>();
                    foreach (var item in logInfoList)
                    {
                        item.system_type_name = item.system_type.GetEnumDescriptionByValue(typeof(SystemType));
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = logInfoList;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            },
            () =>
            {
                resultInfo.Msg = "无对应信息！";
            });
            return resultInfo;
        }

        #endregion
    }
}
